{% extends "base.html" %}

{% block head %}
<style>
    :root {
        --primary-color: #1976d2;
        --primary-hover: #1565c0;
        --border-color: #e0e0e0;
        --light-gray: #f5f5f5;
        --text-color: #333;
        --shadow-color: rgba(0, 0, 0, 0.1);
    }

    body {
        color: var(--text-color);
        background-color: #f8f9fa;
    }

    .container {
        min-width: 800px;
        margin: 0 auto;
    }

    /* 卡片样式 */
    .card {
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 4px var(--shadow-color);
        padding: 20px;
        margin-bottom: 20px;
    }

    .card-header {
        margin: -20px -20px 20px;
        padding: 15px 20px;
        background: var(--light-gray);
        border-radius: 8px 8px 0 0;
        border-bottom: 1px solid var(--border-color);
    }

    .card-header h2 {
        margin: 0;
        font-size: 1.5rem;
        color: var(--primary-color);
    }

    .card-header .card-header_text {
        font-size: 12px;
        font-weight: 400;
        color: rgba(128, 128, 128, 1);
    }

    /* 表格容器样式优化 */
    .table-wrapper {
        position: relative;
        background: white;
    }

    .table-container {
        width: 100%;
        overflow-x: auto;
        position: relative;
        max-height: 600px;
        overflow-y: auto;
        scrollbar-width: thin;
        scrollbar-color: var(--primary-color) var(--light-gray);
    }

    /* 自定义滚动条样式 */
    .table-container::-webkit-scrollbar {
        width: 8px;
        height: 8px;
    }

    .table-container::-webkit-scrollbar-track {
        background: var(--light-gray);
        border-radius: 4px;
    }

    .table-container::-webkit-scrollbar-thumb {
        background: var(--primary-color);
        border-radius: 4px;
    }

    .table-container::-webkit-scrollbar-thumb:hover {
        background: var(--primary-hover);
    }

    /* 滑动指示器 */
    .scroll-indicator {
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
        background: rgba(0, 0, 0, 0.5);
        color: white;
        padding: 8px;
        border-radius: 4px;
        font-size: 12px;
        opacity: 0;
        transition: opacity 0.3s;
        pointer-events: none;
        z-index: 99;
    }

    .scroll-indicator.visible {
        opacity: 1;
    }

    /* 表格样式优化 */
    .result-table {
        width: 100%;
        border-collapse: separate;
        border-spacing: 0;
        margin: 0;
        font-size: 12px;
        min-width: 1200px;
    }

    .result-table th {
        background: #e6f7ff;
        color: #0050b3;
        font-weight: normal;
        position: sticky;
        top: 0;
        z-index: 1;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        min-width: 120px;
        padding: 8px 6px;
        line-height: 1.4;
    }

    .result-table th:hover {
        overflow: visible;
        white-space: nowrap;
        background: #e6f7ff;
        position: relative;
        z-index: 3;
    }

    .result-table td {
        border: 1px solid #d9d9d9;
        padding: 6px 4px;
        text-align: left;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 150px;
    }

    .result-table tr:nth-child(even) {
        background: #f5faff;
    }

    .result-table td:hover {
        overflow: visible;
        white-space: normal;
        word-break: break-all;
        position: relative;
        z-index: 2;
        background: #fff;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }

    /* 分页控件美化 */
    .pagination-container {
        background: white;
        padding: 15px;
        border-top: 1px solid var(--border-color);
        border-radius: 0 0 8px 8px;
        display: flex;
        justify-content: flex-end;
        margin-top: 12px;
        gap: 8px;
    }

    #total-records {
        color: #555;
        font-size: 13px;
        margin-right: 16px;
    }

    .pagination {
        display: flex;
        justify-content: center;
        gap: 8px;
    }

    .pagination button {
        padding: 4px 12px;
        border: 1px solid #d9d9d9;
        border-radius: 4px;
        background: #fff;
        cursor: pointer;
    }

    .pagination button:disabled {
        background: #f5f5f5;
        cursor: not-allowed;
    }

    .pagination button.active {
        background: #1890ff;
        color: white;
        border-color: #1890ff;
    }

    .pagination-ellipsis {
        color: #555;
        padding: 0 8px;
    }

    /* 表单样式优化 */
    .form-group {
        margin-bottom: 20px;
    }

    .form-label {
        display: block;
        margin-bottom: 8px;
        font-weight: 500;
    }

    .form-control {
        width: 100%;
        padding: 8px 12px;
        border: 1px solid var(--border-color);
        border-radius: 4px;
        font-size: 14px;
    }

    .checkbox-group {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;
        padding: 10px;
        background-color: var(--light-gray);
        border-radius: 4px;
    }

    .checkbox-item {
        min-width: 120px;
        display: flex;
        align-items: center;
    }

    .form-check-input {
        margin-right: 6px;
    }

    .form-check-label {
        font-size: 14px;
        user-select: none;
    }

    .btn {
        display: inline-block;
        padding: 8px 16px;
        font-size: 14px;
        font-weight: 500;
        text-align: center;
        text-decoration: none;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.2s;
        border: 1px solid transparent;
    }

    .btn-primary {
        background-color: var(--primary-color);
        color: white;
        border: none;
    }

    .btn-primary:hover {
        background-color: var(--primary-hover);
    }

    .btn-outline-primary {
        background-color: transparent;
        border-color: var(--primary-color);
        color: var(--primary-color);
    }

    .btn-outline-primary:hover {
        background-color: var(--primary-color);
        color: white;
    }

    .btn-sm {
        padding: 4px 12px;
        font-size: 12px;
    }

    .select-all-btn {
        margin-bottom: 10px;
    }

    /* 加载动画 */
    .loading {
        display: none;
        text-align: center;
        margin: 20px 0;
    }

    .loading.active {
        display: block;
    }

    /* 错误消息 */
    .error-message {
        color: red;
        margin: 10px 0;
        display: none;
    }

    /* 下载按钮 */
    .download-btn {
        margin-top: 10px;
        display: none;
    }

    /* 字段选择样式 */
    .field-selection {
        margin: 20px 0;
        padding: 15px;
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 4px var(--shadow-color);
        display: none;
    }

    .field-selection.visible {
        display: block;
    }

    .field-selection-title {
        font-weight: 600;
        margin-bottom: 10px;
        color: var(--primary-color);
    }

    .field-selection-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        gap: 10px;
        margin-top: 10px;
    }

    .field-checkbox {
        display: flex;
        align-items: center;
        padding: 8px;
        background: var(--light-gray);
        border-radius: 4px;
        cursor: pointer;
        transition: background-color 0.2s;
    }

    .field-checkbox:hover {
        background-color: var(--menu-hover);
    }

    .field-checkbox input {
        margin-right: 8px;
    }

    /* 按钮组样式 */
    .button-group {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .button-group > * {
        margin: 0 !important;
    }

    /* 模态框样式 */
    .modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 1000;
    }

    .modal.visible {
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .modal-content {
        background-color: white;
        padding: 24px;
        border-radius: 8px;
        width: 90%;
        max-width: 800px;
        max-height: 90vh;
        overflow-y: auto;
        position: relative;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }

    .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 16px;
        border-bottom: 1px solid var(--border-color);
    }

    .modal-title {
        font-size: 20px;
        font-weight: 600;
        color: var(--text-color);
        margin: 0;
    }

    .modal-close {
        background: none;
        border: none;
        font-size: 24px;
        color: var(--text-color);
        cursor: pointer;
        padding: 4px;
        line-height: 1;
    }

    .modal-close:hover {
        color: var(--primary-color);
    }

    .modal-body {
        margin-bottom: 20px;
    }

    .modal-footer {
        display: flex;
        justify-content: flex-end;
        gap: 12px;
        padding-top: 16px;
        border-top: 1px solid var(--border-color);
    }

    /* 字段选择按钮 */
    .field-select-btn {
        margin-left: 12px;
    }

    /* 添加按钮组样式 */
    .action-buttons {
        display: flex;
        align-items: center;
        gap: 15px;
        margin-bottom: 20px;
    }

    /* 修改字典状态样式 */
    .dict-status {
        display: inline-block;
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 14px;
        margin-left: 10px;
    }

    .dict-status.exists {
        background-color: #e8f5e9;
        color: #2e7d32;
    }

    .dict-status.not-exists {
        background-color: #ffebee;
        color: #c62828;
    }

    .dict-status.generating {
        background-color: #fff3e0;
        color: #ef6c00;
        animation: pulse 1.5s infinite;
    }

    @keyframes pulse {
        0% { opacity: 1; }
        50% { opacity: 0.6; }
        100% { opacity: 1; }
    }

    /* 确认对话框样式 */
    .confirm-dialog {
        display: none;
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: white;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        z-index: 1000;
        min-width: 300px;
    }

    .confirm-dialog.visible {
        display: block;
    }

    .dialog-overlay {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.5);
        z-index: 999;
    }

    .dialog-overlay.visible {
        display: block;
    }

    .dialog-buttons {
        display: flex;
        justify-content: flex-end;
        gap: 10px;
        margin-top: 20px;
    }

    /* 筛选条件样式 */
    .filter-section {
        margin: 20px 0;
        padding: 15px;
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 4px var(--shadow-color);
    }

    .filter-title {
        font-weight: 600;
        margin-bottom: 15px;
        color: var(--primary-color);
    }

    .filter-group {
        margin-bottom: 15px;
        display: flex;
        align-items: flex-start;
    }

    .filter-label {
        min-width: 120px;
        font-weight: 500;
        color: #333;
        padding-top: 2px;
    }

    .filter-options {
        display: flex;
        gap: 30px;
        flex-wrap: wrap;
    }

    .filter-item {
        display: flex;
        align-items: center;
        gap: 4px;
    }

    .filter-checkbox {
        width: 16px;
        height: 16px;
        margin: 0;
        cursor: pointer;
    }

    .filter-item label {
        cursor: pointer;
        user-select: none;
        font-size: 14px;
    }

    .filter-buttons {
        margin-top: 20px;
        padding-top: 15px;
        border-top: 1px solid #eee;
    }
</style>
{% endblock %}

{% block content %}
<div class="container">
    <div class="card">
        <div class="card-header">
            <h2>单一销方单位连号模型</h2>
            <div class="card-header_text">
                模型重点关注同一销方单位为购方单位开具的餐费发票连号的情况，防范是否存在开票不合规、虚假招待等问题。利用费用报销票据信息，
                计算同一销方单位同一购方单位开具业务招待餐费发票号的数量差，并判断发票是否连号及连号个数，重点关注连号个数较多的疑点线索。
            </div>
        </div>

        <!-- 操作按钮组 -->
        <div class="action-buttons">
            <div>
                <button type="button" class="btn btn-primary" onclick="showAnalysisConfirm()">分析数据</button>
                <span id="analysisStatus" class="dict-status"></span>
            </div>
            <button type="button" class="btn btn-primary" onclick="loadExistingData()">加载已有数据</button>
        </div>

        <!-- 筛选条件 -->
        <div class="filter-section">
            <div class="filter-title">筛选条件</div>
            
            <!-- 销方单位等级筛选 -->
            <div class="filter-group">
                <div class="filter-label">风险等级：</div>
                <div class="filter-options">
                    <div class="filter-item">
                        <input type="checkbox" id="riskLevel1" class="filter-checkbox">
                        <label for="riskLevel1">一级风险</label>
                    </div>
                    <div class="filter-item">
                        <input type="checkbox" id="riskLevel2" class="filter-checkbox">
                        <label for="riskLevel2">二级风险</label>
                    </div>
                </div>
            </div>

            <!-- 发票金额等级筛选 -->
            <div class="filter-group">
                <div class="filter-label">发票金额等级：</div>
                <div class="filter-options">
                    <div class="filter-item">
                        <input type="checkbox" id="amountLevel1" class="filter-checkbox">
                        <label for="amountLevel1">发票一级</label>
                    </div>
                    <div class="filter-item">
                        <input type="checkbox" id="amountLevel2" class="filter-checkbox">
                        <label for="amountLevel2">发票二级</label>
                    </div>
                </div>
            </div>

            <div class="filter-buttons">
                <button type="button" class="btn btn-outline-primary" onclick="applyFilters()">应用筛选</button>
                <button type="button" class="btn btn-outline-primary" onclick="clearFilters()">清除筛选</button>
            </div>
        </div>

        <!-- 字段选择和下载按钮 -->
        <div class="form-group">
            <div class="button-group">
                <button type="button" class="btn btn-outline-primary field-select-btn" onclick="openFieldSelection()" style="display: none;">选择显示字段</button>
                <button type="button" class="btn btn-outline-primary download-btn" onclick="downloadExcel()" id="downloadBtn" style="display: none;">下载Excel</button>
            </div>
        </div>

        <!-- 错误消息 -->
        <div id="errorMessage" class="error-message"></div>

        <!-- 加载动画 -->
        <div id="loading" class="loading">
            <div class="loading-spinner"></div>
            正在加载数据，请稍候...
        </div>
    </div>

    <!-- 结果表格 -->
    <div id="resultContainer" class="card" style="display: none;">
        <div class="table-wrapper">
            <div class="scroll-indicator">向右滑动查看更多</div>
            <div class="table-container">
                <table class="result-table">
                    <thead>
                        <tr id="tableHeader">
                            <!-- 表头将通过JavaScript动态生成 -->
                        </tr>
                    </thead>
                    <tbody id="tableBody">
                        <!-- 数据行将通过JavaScript动态生成 -->
                    </tbody>
                </table>
            </div>
            <div class="pagination-container">
                <div class="pagination" id="pagination"></div>
            </div>
        </div>
    </div>

    <!-- 字段选择模态框 -->
    <div id="fieldSelectionModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">选择显示字段</h3>
                <button type="button" class="modal-close" onclick="closeFieldSelection()">&times;</button>
            </div>
            <div class="modal-body">
                <button type="button" class="btn btn-outline-primary btn-sm select-all-btn" onclick="toggleSelectAllFields()">全选/取消全选</button>
                <div class="field-selection-grid" id="fieldCheckboxes">
                    <!-- 字段选择项将通过JavaScript动态生成 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-primary" onclick="closeFieldSelection()">取消</button>
                <button type="button" class="btn btn-primary" onclick="applyAndCloseFieldSelection()">确定</button>
            </div>
        </div>
    </div>

    <!-- 确认对话框 -->
    <div class="dialog-overlay" id="dialogOverlay"></div>
    <div class="confirm-dialog" id="confirmDialog">
        <h3>确认分析</h3>
        <p>是否确定要重新分析数据？</p>
        <div class="dialog-buttons">
            <button class="btn btn-outline-primary" onclick="closeDialog()">取消</button>
            <button class="btn btn-primary" onclick="confirmAnalysis()">确定</button>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    // 当前页码和数据缓存
    let currentPage = 1;
    let totalPages = 1;
    let isLoading = false;
    let availableFields = [];
    let selectedFields = [];
    let cachedData = null;
    let originalData = null;
    let itemsPerPage = 20;

    // 页面加载时检查结果文件是否存在
    window.addEventListener('DOMContentLoaded', () => {
        checkResultFileExists();
        checkAnalysisStatus();
    });

    // 检查分析状态
    async function checkAnalysisStatus() {
        try {
            const response = await fetch('/dining-sequence/check-result-file');
            const result = await response.json();
            updateAnalysisStatus(result.exists ? 'exists' : 'not-exists');
        } catch (error) {
            console.error('Error checking analysis status:', error);
            updateAnalysisStatus('not-exists');
        }
    }

    // 更新分析状态显示
    function updateAnalysisStatus(status) {
        const statusElement = document.getElementById('analysisStatus');
        switch(status) {
            case 'exists':
                statusElement.textContent = '已存在数据';
                statusElement.className = 'dict-status exists';
                break;
            case 'not-exists':
                statusElement.textContent = '暂无数据';
                statusElement.className = 'dict-status not-exists';
                break;
            case 'analyzing':
                statusElement.textContent = '分析中...';
                statusElement.className = 'dict-status generating';
                break;
        }
    }

    // 显示确认对话框
    function showAnalysisConfirm() {
        document.getElementById('dialogOverlay').classList.add('visible');
        document.getElementById('confirmDialog').classList.add('visible');
    }

    // 关闭确认对话框
    function closeDialog() {
        document.getElementById('dialogOverlay').classList.remove('visible');
        document.getElementById('confirmDialog').classList.remove('visible');
    }

    // 确认分析
    async function confirmAnalysis() {
        closeDialog();
        await generateAnalysis();
    }

    // 生成分析数据
    async function generateAnalysis() {
        try {
            updateAnalysisStatus('analyzing');
            
            document.getElementById('loading').classList.add('active');
            document.getElementById('errorMessage').style.display = 'none';
            document.getElementById('resultContainer').style.display = 'none';
            document.querySelector('.field-select-btn').style.display = 'none';
            document.getElementById('downloadBtn').style.display = 'none';
            
            const response = await fetch('/dining-sequence/generate-analysis', { method: 'POST' });
            const result = await response.json();
            
            if (result.success) {
                await fetchAllData();
                updateAnalysisStatus('exists');
            } else {
                alert(result.error || '数据分析失败');
                document.getElementById('loading').classList.remove('active');
                updateAnalysisStatus('not-exists');
            }
        } catch (error) {
            console.error('Error:', error);
            alert('数据分析时出错');
            document.getElementById('loading').classList.remove('active');
            updateAnalysisStatus('not-exists');
        }
    }

    // 获取所有数据并缓存
    async function fetchAllData() {
        try {
            document.getElementById('loading').classList.add('active');
            document.getElementById('errorMessage').style.display = 'none';
            document.getElementById('resultContainer').style.display = 'none';
            document.querySelector('.field-select-btn').style.display = 'none';
            document.getElementById('downloadBtn').style.display = 'none';

            const response = await fetch('/dining-sequence/get-data', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    all: true,
                    risk_level_1: document.getElementById('riskLevel1')?.checked || false,
                    risk_level_2: document.getElementById('riskLevel2')?.checked || false,
                    amount_level_1: document.getElementById('amountLevel1')?.checked || false,
                    amount_level_2: document.getElementById('amountLevel2')?.checked || false
                })
            });

            if (!response.ok) {
                const result = await response.json();
                throw new Error(result.error || '加载数据失败');
            }

            const result = await response.json();
            originalData = result.data;
            cachedData = result.data;
            availableFields = result.all_columns.map(column => ({
                id: column,
                name: column
            }));

            if (selectedFields.length === 0) {
                selectedFields = [...availableFields];
            }

            applyFilters();
            
            document.getElementById('downloadBtn').style.display = 'inline-block';
            document.querySelector('.field-select-btn').style.display = 'inline-block';
            
        } catch (error) {
            document.getElementById('errorMessage').textContent = error.message;
            document.getElementById('errorMessage').style.display = 'block';
            document.getElementById('resultContainer').style.display = 'none';
        } finally {
            document.getElementById('loading').classList.remove('active');
        }
    }

    // 加载已有数据
    async function loadExistingData() {
        await fetchAllData();
    }

    // 检查结果文件是否存在
    async function checkResultFileExists() {
        try {
            const response = await fetch('/dining-sequence/check-result-file');
            const result = await response.json();
            const loadButton = document.querySelector('button[onclick="loadExistingData()"]');
            
            if (result.exists) {
                loadButton.style.display = 'inline-block';
            } else {
                loadButton.style.display = 'none';
            }
        } catch (error) {
            console.error('Error checking result file:', error);
        }
    }

    // 显示指定页的数据
    function displayPageData(page = currentPage) {
        if (!cachedData) return;

        currentPage = page;
        const start = (page - 1) * itemsPerPage;
        const end = start + itemsPerPage;
        const pageData = cachedData.slice(start, end);

        // 计算总页数
        totalPages = Math.ceil(cachedData.length / itemsPerPage);

        displayResults({
            data: pageData,
            all_columns: availableFields.map(f => f.id),
            total_pages: totalPages,
            current_page: currentPage,
            total_records: cachedData.length
        });
    }

    // 修改显示结果函数
    function displayResults(result) {
        const container = document.getElementById('resultContainer');
        const tableHeader = document.getElementById('tableHeader');
        const tableBody = document.getElementById('tableBody');

        // 清空现有内容
        tableHeader.innerHTML = '';
        tableBody.innerHTML = '';

        if (!result.data || result.data.length === 0) {
            document.getElementById('errorMessage').textContent = '没有找到数据';
            document.getElementById('errorMessage').style.display = 'block';
            container.style.display = 'none';
            return;
        }

        // 生成表头
        selectedFields.forEach(field => {
            const th = document.createElement('th');
            th.textContent = field.name;
            tableHeader.appendChild(th);
        });

        // 显示数据
        result.data.forEach(row => {
            const tr = document.createElement('tr');
            selectedFields.forEach(field => {
                if (row.hasOwnProperty(field.id)) {
                    const td = document.createElement('td');
                    const value = row[field.id];
                    
                    if (typeof value === 'number') {
                        td.className = 'number';
                        if (field.id.includes('金额') || field.id.includes('票价')) {
                            td.textContent = value.toFixed(2);
                        } else {
                            td.textContent = value;
                        }
                    } else {
                        td.textContent = value || '-';
                    }
                    
                    tr.appendChild(td);
                }
            });
            tableBody.appendChild(tr);
        });

        // 更新分页控件
        updatePagination();

        // 显示结果容器
        container.style.display = 'block';

        // 添加滑动指示器逻辑
        setTimeout(() => {
            const tableContainer = document.querySelector('.table-container');
            const scrollIndicator = document.querySelector('.scroll-indicator');
            
            if (tableContainer && scrollIndicator) {
                const hasHorizontalScroll = tableContainer.scrollWidth > tableContainer.clientWidth;
                scrollIndicator.classList.toggle('visible', hasHorizontalScroll);
                
                tableContainer.addEventListener('scroll', () => {
                    const isScrolledRight = tableContainer.scrollLeft + tableContainer.clientWidth >= tableContainer.scrollWidth;
                    scrollIndicator.classList.toggle('visible', hasHorizontalScroll && !isScrolledRight);
                });
            }
        }, 100);
    }

    // 更新分页控件
    function updatePagination() {
        const pagination = document.getElementById('pagination');
        pagination.innerHTML = '';

        if (totalPages <= 1) return;

        // 上一页按钮
        const prevButton = document.createElement('button');
        prevButton.textContent = '上一页';
        prevButton.disabled = currentPage === 1;
        prevButton.onclick = () => displayPageData(currentPage - 1);
        pagination.appendChild(prevButton);

        // 页码按钮
        let startPage = Math.max(1, currentPage - 2);
        let endPage = Math.min(totalPages, currentPage + 2);

        // 确保显示至少5个页码按钮
        if (endPage - startPage < 4) {
            if (currentPage < totalPages / 2) {
                endPage = Math.min(startPage + 4, totalPages);
            } else {
                startPage = Math.max(endPage - 4, 1);
            }
        }

        // 添加第一页
        if (startPage > 1) {
            const firstButton = document.createElement('button');
            firstButton.textContent = '1';
            firstButton.onclick = () => displayPageData(1);
            pagination.appendChild(firstButton);

            if (startPage > 2) {
                const ellipsis = document.createElement('span');
                ellipsis.textContent = '...';
                ellipsis.className = 'pagination-ellipsis';
                pagination.appendChild(ellipsis);
            }
        }

        // 添加中间页码
        for (let i = startPage; i <= endPage; i++) {
            const pageButton = document.createElement('button');
            pageButton.textContent = i;
            pageButton.classList.toggle('active', i === currentPage);
            pageButton.onclick = () => displayPageData(i);
            pagination.appendChild(pageButton);
        }

        // 添加最后一页
        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                const ellipsis = document.createElement('span');
                ellipsis.textContent = '...';
                ellipsis.className = 'pagination-ellipsis';
                pagination.appendChild(ellipsis);
            }

            const lastButton = document.createElement('button');
            lastButton.textContent = totalPages;
            lastButton.onclick = () => displayPageData(totalPages);
            pagination.appendChild(lastButton);
        }

        // 下一页按钮
        const nextButton = document.createElement('button');
        nextButton.textContent = '下一页';
        nextButton.disabled = currentPage === totalPages;
        nextButton.onclick = () => displayPageData(currentPage + 1);
        pagination.appendChild(nextButton);
    }

    // 字段选择相关函数
    function openFieldSelection() {
        const modal = document.getElementById('fieldSelectionModal');
        modal.classList.add('visible');
        initializeFieldSelection();
    }

    function closeFieldSelection() {
        const modal = document.getElementById('fieldSelectionModal');
        modal.classList.remove('visible');
    }

    function initializeFieldSelection() {
        const container = document.getElementById('fieldCheckboxes');
        container.innerHTML = '';
        
        availableFields.forEach(field => {
            const div = document.createElement('div');
            div.className = 'field-checkbox';
            div.innerHTML = `
                <input type="checkbox" id="field_${field.id}" 
                       ${selectedFields.find(f => f.id === field.id) ? 'checked' : ''}>
                <label for="field_${field.id}">${field.name}</label>
            `;
            container.appendChild(div);
        });
    }

    function toggleSelectAllFields() {
        const checkboxes = document.querySelectorAll('#fieldCheckboxes input[type="checkbox"]');
        const allChecked = Array.from(checkboxes).every(cb => cb.checked);
        checkboxes.forEach(checkbox => checkbox.checked = !allChecked);
    }

    function applyFieldSelection() {
        const checkboxes = document.querySelectorAll('#fieldCheckboxes input[type="checkbox"]:checked');
        selectedFields = Array.from(checkboxes).map(cb => {
            const fieldId = cb.id.replace('field_', '');
            return availableFields.find(f => f.id === fieldId);
        });
        
        if (selectedFields.length === 0) {
            alert('请至少选择一个字段');
            return false;
        }
        
        displayPageData(currentPage);
        return true;
    }

    function applyAndCloseFieldSelection() {
        if (applyFieldSelection()) {
            closeFieldSelection();
        }
    }

    // 应用筛选条件
    function applyFilters() {
        if (!originalData) {
            alert('请先加载数据');
            return;
        }

        // 获取筛选条件
        const riskLevel1 = document.getElementById('riskLevel1').checked;
        const riskLevel2 = document.getElementById('riskLevel2').checked;
        const amountLevel1 = document.getElementById('amountLevel1').checked;
        const amountLevel2 = document.getElementById('amountLevel2').checked;

        // 根据筛选条件筛选数据
        cachedData = originalData.filter(row => {
            if (!riskLevel1 && !riskLevel2 && !amountLevel1 && !amountLevel2) {
                return true; // 如果都没选，显示所有数据
            }

            let matchRisk = true;
            if (riskLevel1 || riskLevel2) {
                matchRisk = (riskLevel1 && row['风险等级'] === '一级') || 
                           (riskLevel2 && row['风险等级'] === '二级');
            }

            let matchAmount = true;
            if (amountLevel1 || amountLevel2) {
                matchAmount = (amountLevel1 && row['发票金额等级'] === '一级') || 
                            (amountLevel2 && row['发票金额等级'] === '二级');
            }

            return matchRisk && matchAmount;
        });

        if (cachedData.length === 0) {
            alert('没有找到符合条件的数据');
            return;
        }

        // 重置分页并显示数据
        currentPage = 1;
        totalPages = Math.ceil(cachedData.length / itemsPerPage);
        displayPageData();
    }

    // 清除筛选条件
    function clearFilters() {
        // 重置复选框状态
        document.getElementById('riskLevel1').checked = false;
        document.getElementById('riskLevel2').checked = false;
        document.getElementById('amountLevel1').checked = false;
        document.getElementById('amountLevel2').checked = false;

        if (originalData) {
            cachedData = originalData;
            totalPages = Math.ceil(cachedData.length / itemsPerPage);
            currentPage = 1;
            displayPageData();
        }
    }

    // 下载Excel函数
    function downloadExcel() {
        if (selectedFields.length === 0) {
            alert('请至少选择一个字段');
            return;
        }

        if (!cachedData || cachedData.length === 0) {
            alert('没有可下载的数据');
            return;
        }

        const params = new URLSearchParams();
        
        // 添加选中的字段
        selectedFields.forEach(field => {
            params.append('fields', field.id);
        });

        // 添加筛选条件
        const riskLevel1 = document.getElementById('riskLevel1').checked;
        const riskLevel2 = document.getElementById('riskLevel2').checked;
        const amountLevel1 = document.getElementById('amountLevel1').checked;
        const amountLevel2 = document.getElementById('amountLevel2').checked;

        // 将筛选条件添加到请求参数
        params.append('risk_level_1', riskLevel1);
        params.append('risk_level_2', riskLevel2);
        params.append('amount_level_1', amountLevel1);
        params.append('amount_level_2', amountLevel2);
        
        const downloadUrl = `/dining-sequence/download-excel?${params.toString()}`;
        
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.style.display = 'none';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
</script>
{% endblock %} 